package tum0r.utils;

import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

/**
 * 工程: OJ<br>
 * 包: tum0r.oj.utils<br>
 * 创建者: tum0r<br>
 * 创建时间: 2020/11/17 22:22<br>
 * <br>
 */
public class DateExtension {
    private static Date add(Date date, int amount, int mode) {
        date = date != null ? date : new Date();
        if (amount == 0) {
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(mode, amount);
        return calendar.getTime();
    }

    public static Date addYears(Date date, int years) {
        return add(date, years, Calendar.YEAR);
    }

    public static Date addMonths(Date date, int months) {
        return add(date, months, Calendar.MONTH);
    }

    public static Date addDays(Date date, int days) {
        return add(date, days, Calendar.DATE);
    }

    public static Date addHours(Date date, int hours) {
        return add(date, hours, Calendar.HOUR);
    }

    public static Date addMinutes(Date date, int minutes) {
        return add(date, minutes, Calendar.MINUTE);
    }

    public static Date addSeconds(Date date, int seconds) {
        return add(date, seconds, Calendar.SECOND);
    }

    public static Date addMilliSeconds(Date date, int milliSeconds) {
        return add(date, milliSeconds, Calendar.MILLISECOND);
    }

    public static Object startTime(Date date) {
        return date != null ? date : 0;
    }

    public static Object endTime(Date date) {
        return date != null ? date.getTime() == 0 ? addDays(new Date(), 1) : addDays(date, 1) : 0;
    }

    public static Date getTimeStart(TimeZone timeZone) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(timeZone);
        calendar.setTimeInMillis(0);
        return calendar.getTime();
    }

    public static Date getTimeStart() {
        return getTimeStart(TimeZone.getDefault());
    }

    private static Date getUTC(Date date, boolean minus) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int zoneOffset = calendar.get(java.util.Calendar.ZONE_OFFSET);
        int dstOffset = calendar.get(java.util.Calendar.DST_OFFSET);
        int value = zoneOffset + dstOffset;
        calendar.add(java.util.Calendar.MILLISECOND, minus ? -value : value);
        return calendar.getTime();
    }

    public static Date getUTCTimeStart() {
        return getUTC(getTimeStart(), true);
    }

    public static Date toUTCTime(Date date) {
        return getUTC(date, true);
    }

    public static Date toLocalTime(Date date) {
        return getUTC(date, false);
    }

    public static Date now() {
        return new Date();
    }

    public static Date today() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), 0, 0, 0);
        return calendar.getTime();
    }
}
